package com.jay.net.clazz.socket;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

class ConcurrentTCPServer implements Runnable {
	public static final int BUFFER_SIZE = 128 * 1024;// 128k
	public static final int TIMEOUT = 30 * 1000; // 30s
	ServerSocket serverSocket;

	ConcurrentTCPServer(int port) throws IOException {
		// (Don’t specify localAddress for ServerSocket)
		serverSocket = new ServerSocket(port);
		// Set receive buffer size for accepted sockets
		// before accepting any, i.e. before they are connected
		serverSocket.setReceiveBufferSize(BUFFER_SIZE);
		// Don’t set server socket timeout
	}

	public void run() {
		for (;;) {
			try {
				Socket socket = serverSocket.accept();
				// set send buffer size
				socket.setSendBufferSize(BUFFER_SIZE);
				// Don’t wait forever for client requests
				socket.setSoTimeout(TIMEOUT);
				// despatch connection handler on new thread
				new Thread(new ConnectionHandler(socket)).start();
			} catch (IOException e) {
				/* Exception handling, not shown … */
			}
		} // end for (;;)
	} // end run()
} // end class